import 'package:basic/basic.dart';
import 'package:core/src/cache/app_storage_manager.dart';
import 'package:flutter/material.dart';

import '../bean/user.dart';
import '../constant.dart';

bool loggedIn() => UserManager.getToken() != null;

///用户管理类 用户信息缓存 状态查询等功能
class UserManager {
  static String tag = "UserManager";

  //是否登录
  static bool isLogin(
    BuildContext context, {
    bool showLoginTip = true,
    bool jumpToLogin = true,
    Function(User user)? loginCallback,
  }) {
    if (!loggedIn()) {
      if (showLoginTip) ToastUtil.show(msg: '请先登录再进行操作');

      if (jumpToLogin) {
        // NavigatorHelper.pushRouteName(context, RouteNames.login).then((user) {
        //   if (user != null) loginCallback?.call(user as User);
        // });
      }
      return false;
    }
    return true;
  }

  //保存token 和 user
  static void saveTokenUser(String? token, User? user) {
    saveToken(token);
    saveUser(user);
  }

  //保存token
  static void saveToken(String? token) {
    if (token != null) {
      StorageManager.localStorage.setItem(AppLocalStorageKey.token, token);
    }
  }

  //移除token 和 用户
  static void removeTokenUser() {
    LogUtil.v("清除本地 token user removeTokenUser()---->> ", tag: tag);
    StorageManager.localStorage.removeItem(AppLocalStorageKey.token);
    StorageManager.localStorage.removeItem(AppLocalStorageKey.user);
  }

  /// 获取当前登录用户token
  static String? getToken() {
    String? token = StorageManager.localStorage.getItem(
      AppLocalStorageKey.token,
    );
    return (token?.isNotEmpty) ?? false ? token : null;
  }

  // 保存用户
  static void saveUser(User? user) async {
    if (user == null) return;
    await AppStorageManager.setItem(AppLocalStorageKey.user, user.toJson());
  }

  /// 获取当前登录用户
  static User? getUserInfo() {
    var userMap = StorageManager.localStorage.getItem(AppLocalStorageKey.user);
    User? user = userMap == null ? null : User.fromJson(userMap as Map<String, dynamic>);

    return (getToken()?.isNotEmpty) ?? false ? user : null;
  }

  ///获取用户id
  static int? getUserId() {
    return getUserInfo()?.userId ?? 0;
  }

  ///获取用户loginName
  static String getUserLoginName() {
    return getUserInfo()?.nickName ?? '';
  }

  static void saveUserLoginName(String nickname) {
    User? user = getUserInfo();
    user?.nickName = nickname;
    saveUser(user);
  }

  ///获取用户手机号
  static String getUserPhoneNumber() {
    return getUserInfo()?.mobile ?? '';
  }

  ///获取用户头像
  static String getUserAvatar() {
    return getUserInfo()?.avatar ?? '';
  }

  static void saveUserAvatar(String avatar) {
    User? user = getUserInfo();
    user?.avatar = avatar;
    saveUser(user);
  }

  ///获取用户密码
  static String getPassword() {
    return getUserInfo()?.password ?? '';
  }

  static void saveUserPassword(String psw) {
    User? user = getUserInfo();
    user?.password = psw;
    saveUser(user);
  }
}
